//
//  FHRefreshControl.swift
//  WeiBo
//
//  Created by qfh on 16/7/16.
//  Copyright © 2016年 qiufuhe. All rights reserved.
//

import UIKit

// 下拉状态枚举
enum FHRefreshControlState: Int {
    
    
    // 下拉刷新
    case Normal = 0
    // 松手刷新
    case Pulling = 1
    // 正在刷新
    case Refreshing = 2
    
}
// refresh 的高度
private let FHRefreshcontrolHeight: CGFloat = 50

class FHRefreshControl: UIControl {
    
    
    private var refreshControlState: FHRefreshControlState = .Normal {
    
        didSet {
        
            switch refreshControlState {
                
            case .Normal:
                
                messageLabel.text = "下拉刷新"
                
                indicatorView.hidden = true
                
                iconImageView.hidden = false
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.iconImageView.transform = CGAffineTransformIdentity
            
                    
                })
                
                
                if oldValue == .Refreshing {
                
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        
                        self.currentScrollView?.contentInset.top -= FHRefreshcontrolHeight
                    })
                
                }
                
                
                
            case .Pulling:
                
                
                messageLabel.text = "松手刷新"
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    
                    self.iconImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                    
                })
                
                
                
            case .Refreshing:
                
                iconImageView.hidden = true
                
                indicatorView.hidden = false
                
                messageLabel.text = "正在刷新"
                
                indicatorView.startAnimating()
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.currentScrollView?.contentInset.top += FHRefreshcontrolHeight
                    
                })

                
                
            }
            
            
        
        }
    
    
    }

    
    private var currentScrollView: UIScrollView?
    
    // 下拉箭头
    private lazy var iconImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    // messageLbael 
    
    private lazy var messageLabel: UILabel = {
    
        let label = UILabel()
        
        label.textColor = UIColor.grayColor()
        
        label.font = UIFont.systemFontOfSize(12)
        
        label.text = "下拉刷新"
    
        return label
    }()
    
    //  菊花转
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setupUI() {
    
    
        backgroundColor = UIColor.redColor()
    
        addSubview(iconImageView)
        
        addSubview(messageLabel)
        
        addSubview(indicatorView)
        
        
        iconImageView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -35))
        
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        
        
        
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .Leading, relatedBy: .Equal, toItem: iconImageView, attribute: .Trailing, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        
        
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .CenterX, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterX, multiplier: 1, constant: 0))
  
    }
    
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        guard let scorllView = newSuperview as? UIScrollView else {
        
            return
        }
        
        self.frame.size = CGSize(width: scorllView.frame.size.width, height: FHRefreshcontrolHeight)
        
        self.frame.origin.y = -FHRefreshcontrolHeight
        
        currentScrollView = scorllView
        
//        kvo
        
        scorllView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
        
        
    }
    
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        guard let scollerView = currentScrollView else {
        
            return
        }
        
        
        
        
       
        
        if scollerView.dragging {
            
//             print(abs(FHRefreshcontrolHeight + scollerView.contentInset.top))
            
            if scollerView.contentOffset.y < -(FHRefreshcontrolHeight + scollerView.contentInset.top)  && refreshControlState == .Normal {
                
                refreshControlState = .Pulling
                
            } else if scollerView.contentOffset.y > -(FHRefreshcontrolHeight + scollerView.contentInset.top) && refreshControlState == .Pulling {
            
                refreshControlState = .Normal
     
            
            }
            
            
        } else if refreshControlState == .Pulling {
        
        
            refreshControlState = .Refreshing
            
            sendActionsForControlEvents(.ValueChanged)
        
        
        }
        
    
        
        
    }
    
    
    // MARK: -  结束动画
    
    
    func endRefreshing()
    {
        refreshControlState = .Normal
        
        
    }
    
    deinit {
        
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
}
